<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" v-show="activeKey=='cg'" @click="addPackage" icon="plus" style="margin-left: 8px">添加入库单</a-button>
      <a-button @click="handleAdd" v-show="activeKey!='cg'" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('包材入库单')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <a-tabs v-model="activeKey">
      <a-tab-pane key="cg" tab="采购订单">
        <div>
          <div class='table-page-search-wrapper'>

          </div>
          <a-table
            ref='procTable'
            size='middle'
            bordered
            rowKey='id'
            class='j-table-force-nowrap'
            :scroll='{x:true}'
            :columns='table1.columns'
            :dataSource='table1.dataSource'
            :pagination='table1.ipagination'
            :loading='table1.loading'
            :rowSelection='{selectedRowKeys: table1.selectedRowKeys, onChange: onSelectChangeTab1}'
          >
            <template slot='htmlSlot' slot-scope='text'>
              <div v-html='text'></div>
            </template>
          </a-table>
        </div>
      </a-tab-pane>
      <a-tab-pane key='rk' tab='入库单' force-render>
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row >
                <a-col :xl="4" :lg="4" :md="4" :sm="4">
                  <a-form-item label="">
                    <a-radio-group v-model="queryParam.status" @change="onRadioChange">
                      <a-radio :value="0">已审批</a-radio>
                      <a-radio :value="1">需修改</a-radio>
                      <a-radio :value="2">入库完成</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="6" :sm="6">
                  <a-form-item label="起始日期">
                    <a-date-picker type="ge" v-model="queryParam.createTime_begin" :format="dateFormat" :valueFormat="dateFormat" @change="changeDate"/>
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="7" :md="8" :sm="24">
                  <a-form-item label="截止日期">
                    <a-date-picker type="le" v-model="queryParam.createTime_end"  :format="dateFormat" :valueFormat="dateFormat" @change="changeDate"/>
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="7" :md="8" :sm="24">
                  <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                    <!-- <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>-->
                    <!-- <a @click="handleToggleSearch" style="margin-left: 8px">-->
                    <!-- {{ toggleSearchStatus ? '收起' : '展开' }}-->
                    <!-- <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>-->
                    <!-- </a>-->
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <div>
            <tsl-simple-query :data-source="dataSource" :columns="columns" @searchQueryTab="searchQueryTab"
                              @clearQueryTab="clearQueryTab" @initQueryColumns="initQueryColumns"></tsl-simple-query>
          </div>
          <div>
            <TslSettingCloumns :selectedRowKeys="selectedRowKeys" :settingColumns="settingColumns" :defColumns="defColumns"
                               @onColSettingsChange="onColSettingsChange" @onClearSelected="onClearSelected"></TslSettingCloumns>
            <a-table
              ref="table"
              size="middle"
              bordered
              :rowKey="(record,index)=>{return record.detailId}"
              class="j-table-force-nowrap"
              :scroll="{x:true}"
              :columns="columns"
              :dataSource="dataSource"
              :pagination="ipagination"
              :loading="loading"
              :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
              @change="handleTableChange">

              <template slot="htmlSlot" slot-scope="text">
                <div v-html="text"></div>
              </template>
              <template slot="imgSlot" slot-scope="text,record">
                <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
              </template>
              <template slot="fileSlot" slot-scope="text">
                <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
                <a-button
                  v-else
                  :ghost="true"
                  type="primary"
                  icon="download"
                  size="small"
                  @click="downloadFile(text)">
                  下载
                </a-button>
              </template>

              <span slot="action" slot-scope="text, record">
                <a @click="handleEdit(record)">编辑</a>

                <a-divider type="vertical" />
                <a-dropdown>
                  <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a @click="handleDetail(record)">详情</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                        <a>删除</a>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </span>

            </a-table>
          </div>
      </a-tab-pane>
    </a-tabs>
    <package-storage-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import PackageStorageModal from './modules/PackageStorageModal'
  import '@/assets/less/TableExpand.less'
  import TslSettingCloumns from '@comp/tsl/TslSettingCloumns.vue'
  import TslSimpleQuery from '@comp/tsl/TslSimpleQuery.vue'
  import { getAction } from '@api/manage'
  import { filterObj } from '@/utils/util'
  import moment from 'dayjs'

  export default {
    name: "PackageStorageList",
    mixins:[JeecgListMixin],
    components: {
      PackageStorageModal,TslSettingCloumns,TslSimpleQuery
    },
    data () {
      return {
        description: '包材入库单管理页面',
        // 表头
        disableMixinCreated: true,
        isOpenSettingColumns: true,
        moment,
        dateFormat: 'YYYY-MM-DD',
        activeKey: 'rk',
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'编号',
            align:"center",
            dataIndex: 'code'
          },
          {
            title:'类型',
            align:"center",
            dataIndex: 'storageType_dictText'
          },
          {
            title:'供货单位',
            align:"center",
            dataIndex: 'supplierId'
          },
          {
            title:'物料编号',
            align:"center",
            dataIndex: 'materialCode'
          },
          {
            title:'名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'noneSpec'
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'meUnit_dictText'
          },
          {
            title:'数量',
            align:"center",
            dataIndex: 'num'
          },
          {
            title:'质检结果',
            align:"center",
            dataIndex: 'qcStatus_dictText'
          },
          {
            title:'生产日期',
            align:"center",
            dataIndex: 'manufactureDate'
          },
          {
            title:'制单部门',
            align:"center",
            dataIndex: 'sysOrgCode'
          },
          {
            title:'限用日期',
            align:"center",
            dataIndex: 'expiryDate'
          },
          {
            title:'制单日期',
            align:"center",
            dataIndex: 'createTime'
          },
          {
            title:'宝洁供应商编码',
            align:"center",
            dataIndex: 'bjSupplierCode'
          },
          {
            title:'宝洁采购订单号',
            align:"center",
            dataIndex: 'bjProcurementCode'
          },
          {
            title:'宝洁供应商',
            align:"center",
            dataIndex: 'bjProcurementName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            customRender: (text, record, index) => {
              const obj = {
                children: [
                  //record.status === 0 || record.status === 2
                  (( record.status == 1) && (record.qcStatus == 0 )) && (
                    <a onClick={() => this.handleEdit(record)}>编辑</a>
                  ),
                  (( record.status == 1) && (record.qcStatus == 0 ))  && (
                    <a-divider type='vertical'></a-divider>
                  ),
                  // ( (( record.status == 0) && (record.qcStatus === 0)) || (record.storageType == 1) || ( record.status == 2))  && (
                  // <a onClick={() => this.retract(record)}>撤回</a>
                  // ),
                  // (( record.status == 0) && (record.qcStatus === 0 ) || (record.storageType == 1) || ( record.status == 2))  && (
                  // <a-divider type='vertical' />
                  // ),
                  ( (( record.status == 0) && (record.qcStatus == 0)) || (record.storageType == 1) )  && (
                    <a onClick={() => this.retract(record)}>撤回</a>
                  ),
                  (( record.status == 0) && (record.qcStatus == 0 ) || (record.storageType == 1) )  && (
                    <a-divider type='vertical' />
                  ),
                  <a-dropdown>
                    <a class='ant-dropdown-link'>更多 <a-icon type='down' /></a>
                    <a-menu slot='overlay'>
                      <a-menu-item>
                        <a onClick={() => this.handleDetail(record)}>详情</a>
                      </a-menu-item>
                      <a-menu-item>
                        <a-popconfirm title='确定删除吗?' onConfirm={() => this.handleDelete(record.id)}>
                          <a>删除</a>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                ],
                attrs: {}
              }
              // // 判断是否需要合并行
              if (index > 0 && record.id === this.dataSource[index - 1].id) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter(item => item.id === record.id).length
              }
              return obj
            }
            // scopedSlots: { customRender: 'action' },
          }
        ],
        table1: {
          selectedRowKeys: [],
          selectionRows: [],
          loading: false,
          columns: [
            {
              title: '#',
              dataIndex: '',
              key: 'rowIndex',
              width: 60,
              align: 'center',
              customRender: function(t, r, index) {
                return parseInt(index) + 1
              }
            },
            {
              title: '编号',
              align: 'center',
              dataIndex: 'code',
              scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title: '物料编号',
              align: 'center',
              dataIndex: 'materialCode',
              scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title: '物料名称',
              align: 'center',
              dataIndex: 'materialName',
              scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title: '规格',
              align: 'center',
              dataIndex: 'spec',
              scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title: '订单数量',
              align: 'center',
              dataIndex: 'procurementNum',
              scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title:'已到货数量',
              align:"center",
              dataIndex: 'arrivalNum',
              scopedSlots: { customRender: 'htmlSlot' },
            },
            {
              title: '未到货数量',
              align: 'center',
              dataIndex: 'originalNum',
              // scopedSlots: { customRender: 'htmlSlot' },
              customRender: (text, record, index) => {
                // Provide default value if baseValue is missing
                if(record.arrivalNum){
                  return record.procurementNum - record.arrivalNum;
                }
                return record.procurementNum;
              }
            },
            {
              title: '价格',
              align: 'center',
              dataIndex: 'procurementArrayPrice',
              scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title: '制单人',
              align: 'center',
              dataIndex: 'createBy',
              scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title: '制单日期',
              align: 'center',
              dataIndex: 'createTime'
              , scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title: '制单部门',
              align: 'center',
              dataIndex: 'sysOrgCode',
              scopedSlots: { customRender: 'htmlSlot' }
            },
            {
              title: '供方单位',
              align: 'center',
              dataIndex: 'supplierId_dictText',
              scopedSlots: { customRender: 'htmlSlot' }
            }

          ],
          dataSource: [],
          dataSourceBack: [],
          ipagination: {
            current: 1,
            pageSize: 30,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
              return range[0] + '-' + range[1] + ' 共' + total + '条'
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
          }
        },
        url: {
          list: "/business/packageStorage/list",
          delete: "/business/packageStorage/delete",
          deleteBatch: "/business/packageStorage/deleteBatch",
          exportXlsUrl: "/business/packageStorage/exportXls",
          importExcelUrl: "business/packageStorage/importExcel",
          proclist: '/business/bussMaterialProcurement/page/list'
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.loadProcData()
      this.queryParam.createTime_begin = moment().subtract(7, 'days').format(this.dateFormat)
      this.queryParam.createTime_end = moment().format(this.dateFormat)
      this.loadData();
      this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      retract(record){
        getAction("/business/bussStorageNotice/retract",{id:record.id}).then(res=>{
          if(res.code === 200){
            this.loadData()
          }else{
            this.$message.error(res.message)
          }
        }).catch(res =>{
          this.$message.error(res.message)
        }).finally(() =>{
          // this.confirmLoading = false
        })
      },
      onRadioChange() {
        this.loadData()
      },
      changeDate() {
        this.$forceUpdate()
      },
      addPackage(){
        const rows = this.table1.selectionRows
        if (rows.length == 0) {
          this.$message.warn('请选择采购单！')
          return
        }
        const supplierId = rows[0].supplierId
        const newrows = rows.filter(item => item.supplierId === supplierId)
        if (newrows.length != rows.length) {
          this.$message.warn('一个入库通知单单只能是同一个供应商！')
          return
        }
        //
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
        // 添加入库通知单
        this.$nextTick(() => {
          this.$refs.modalForm.$refs.realForm.procSelectRows = rows
          this.$refs.modalForm.$refs.realForm.addProc()
        })
      },
      getProcQueryParams() {
        //获取查询条件
        var param = {};
        var param = Object.assign({}, {}, {}, {});
        console.log('canshu',param)
        param.field = this.getTable1QueryField();
        param.ext = this.ext
        param.pageNo = this.table1.ipagination.current;
        param.pageSize = this.table1.ipagination.pageSize;
        param.status = '0,2'
        param.procurementType = 0
        return filterObj(param);
      },
      getTable1QueryField() {
        //TODO 字段权限控制
        var str = "id,";
        this.table1.columns.forEach(function (value) {
          str += "," + value.dataIndex;
        });
        return str;
      },
      loadProcData() {
        //加载数据 若传入参数1则加载第一页的内容
        // if (arg === 1) {
        //   this.ipagination.current = 1;
        // }
        // var params = {}
        var params = this.getProcQueryParams()//查询条件
        this.table1.loading = true
        getAction(this.url.proclist, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.table1.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.table1.ipagination.total = res.result.total
            } else {
              this.table1.ipagination.total = 0
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.table1.loading = false
        })
      },
      onSelectChangeTab1(selectedRowKeys, selectionRows) {
        this.table1.selectedRowKeys = selectedRowKeys
        this.table1.selectionRows = selectionRows
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'supplierId',text:'供货商单位',dictCode:''})
        fieldList.push({type:'string',value:'type',text:'类型',dictCode:''})
        fieldList.push({type:'string',value:'lotNumber',text:'批次号',dictCode:''})
        fieldList.push({type:'datetime',value:'enteringDate',text:'进场日期'})
        fieldList.push({type:'string',value:'bjSupplierCode',text:'宝洁供应商编码',dictCode:''})
        fieldList.push({type:'string',value:'bjProcurementCode',text:'宝洁采购订单号',dictCode:''})
        fieldList.push({type:'string',value:'bjSupplierName',text:'宝洁供应商',dictCode:''})
        fieldList.push({type:'string',value:'status',text:'状态',dictCode:''})
        fieldList.push({type:'string',value:'code',text:'编号',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>